package com.zhkj.txg.module.home.popup

import android.content.Context
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.MarketCatePopupAdapter
import com.zhkj.txg.module.home.entity.NavigationEntity
import razerdp.basepopup.BasePopupWindow

class MarketTabPopupWindow(
    context: Context,
    var list: MutableList<NavigationEntity> = mutableListOf(),
    val select: (position: Int) -> Unit
) : BasePopupWindow(context) {

    private var adapter: MarketCatePopupAdapter? = null

    init {
        popupGravity = Gravity.CENTER
    }

    override fun onCreateContentView(): View = createPopupById(R.layout.popup_market_tab)

    override fun showPopupWindow() {
        super.showPopupWindow()
        adapter?.replaceData(list)
    }

    override fun onViewCreated(contentView: View?) {
        contentView?.findViewById<RecyclerView>(R.id.rvMarketTab)?.let {
            it.layoutManager = GridLayoutManager(context, 3)
            adapter = MarketCatePopupAdapter().apply {
                setOnItemClickListener { _, _, position ->
                    select(position)
                    dismiss()
                }
            }
            it.adapter = adapter
        }
    }

    fun setSelectedPosition(index: Int): MarketTabPopupWindow {
        if (list.size > index) {
            adapter?.selectPosition(index)
            adapter?.notifyDataSetChanged()
        }
        return this
    }
}